package com.yjzx.util.racket.config;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.yjzx.util.common.util.ExceptionUtil;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author yjzx
 * @date 2024/8/17
 * @description 消息生产者
 */
@Component
public class SendMessage {
    private final Producer producer;

    private final Map<String, RocketProperties.ProductProperties> exchangeMap;

    public SendMessage(Producer producer, RocketProperties rocketProperties) {
        this.producer = producer;
        this.exchangeMap = rocketProperties.getExchangeMap();
    }


    public void sendMessage(String exchangeName, Object msg) {
        sendMessage(exchangeName, msg, 0);
    }

    /**
     * 定时消息
     * @param exchangeName 消息处理配置名
     * @param msg 消息
     * @param delayTime 定时时间（秒）
     */
    public void sendMessage(String exchangeName, Object msg, long delayTime) {
        if (exchangeMap.containsKey(exchangeName)) {
            sendMessage(exchangeMap.get(exchangeName), msg, delayTime);
        }
        throwException("exchangeName is not exist");
    }
    public void sendMessage(RocketProperties.ProductProperties properties, Object msg) {
        sendMessage(properties, msg, 0);
    }
    public void sendMessage(RocketProperties.ProductProperties properties, Object msg, long delayTime) {
        Message message = new Message(properties.getTopic(), properties.getTag(), JSONObject.toJSONBytes(msg));
        if (delayTime > 0) {
            message.setStartDeliverTime(System.currentTimeMillis() + (delayTime* 1000L));
        }
        producer.send(message);
    }
    public static void throwException(String msg) {
        ExceptionUtil.throwException(new RuntimeException(msg),1);
    }

    public static void main(String[] args) {
        throwException("异常");
    }
}
